package com.jinyijia.admin.interfaces;

import com.alibaba.fastjson.JSONObject;
import com.jinyijia.admin.config.Constant;
import com.jinyijia.admin.interfaces.dto.TemplateSaveDTO;
import com.jinyijia.admin.interfaces.utils.HttpHeadUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestOperations;

import java.util.Objects;

@RestController
@RequestMapping(Constant.Path.PRODUCT_TEMPLATE)
public class ProductTemplateController {

  @Autowired
  private RestOperations restOperations;

  @Value("${jinYiJia.api.productTemplates}")
  private String apiPath;

  /**
   * 根据类目id获取产品模板属性
   * @return
   */
  @GetMapping("/{categoryId}")
  public ResponseEntity getTemplateByCategoryId(@PathVariable Long categoryId){
    return restOperations.getForEntity(apiPath+"?categoryId={1}",JSONObject.class, categoryId);
  }

  /**
   * 提交保存和修改
   * @param dto
   * @return
   */
  @PostMapping
  public ResponseEntity saveTemplate(@RequestBody TemplateSaveDTO dto) {
    StringBuffer url = new StringBuffer(apiPath).append("?categoryId=").append(dto.getCategoryId());
    if (Objects.nonNull(dto.getMajorProperties())) {
      String majorData = "";
      for (String name : dto.getMajorProperties()) {
        majorData = majorData + name + ",";
      }
      url.append("&majorProperties=").append(majorData);
    }
    if (Objects.nonNull(dto.getAttributes())) {
      String attrData = "";
      for (String name : dto.getAttributes()) {
        attrData = attrData + name + ",";
      }
      url.append("&attributes=").append(attrData);
    }
    JSONObject object = restOperations.postForEntity(url.toString(), null, JSONObject.class).getBody();
    return ResponseEntity.ok(object);
  }

  @DeleteMapping("/{id}")
  public ResponseEntity deleteTemplate(@PathVariable Integer id) {
    HttpEntity<String> httpEntity = HttpHeadUtil.addHeader();
    StringBuffer url = new StringBuffer(apiPath).append("?categoryId=" + id);
    String response = restOperations.exchange(url.toString(), HttpMethod.DELETE, httpEntity, String.class).getBody();
    return ResponseEntity.ok(response);
  }
}
